package com.jia.lightrailsystem

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Window
import android.widget.TextView
import com.google.android.material.progressindicator.LinearProgressIndicator
import java.text.DecimalFormat

class DownloadProgressDialog(context: Context) : Dialog(context) {
    private lateinit var progressBar: LinearProgressIndicator
    private lateinit var tvProgress: TextView
    private lateinit var tvSpeed: TextView
    private lateinit var tvFileSize: TextView
    private lateinit var tvFileName: TextView
    
    private var startTime: Long = 0
    private var lastDownloadedSize: Long = 0
    private var totalSize: Long = 0
    private val decimalFormat = DecimalFormat("#.##")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.dialog_download_progress)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        setCancelable(false)

        initViews()
    }

    private fun initViews() {
        progressBar = findViewById(R.id.progressBar)
        tvProgress = findViewById(R.id.tvProgress)
        tvSpeed = findViewById(R.id.tvSpeed)
        tvFileSize = findViewById(R.id.tvFileSize)
        tvFileName = findViewById(R.id.tvFileName)
    }

    fun setFileName(fileName: String) {
        tvFileName.text = fileName
    }

    fun setTotalSize(size: Long) {
        totalSize = size
        updateFileSize(0)
    }

    fun updateProgress(downloadedSize: Long) {
        if (startTime == 0L) {
            startTime = System.currentTimeMillis()
            lastDownloadedSize = downloadedSize
        }

        val progress = (downloadedSize * 100 / totalSize).toInt()
        progressBar.progress = progress
        tvProgress.text = "$progress%"

        // 计算下载速度
        val currentTime = System.currentTimeMillis()
        val timeDiff = (currentTime - startTime) / 1000.0
        if (timeDiff > 0) {
            val speed = ((downloadedSize - lastDownloadedSize) / timeDiff).toLong()
            tvSpeed.text = "${formatFileSize(speed)}/s"
            lastDownloadedSize = downloadedSize
            startTime = currentTime
        }

        updateFileSize(downloadedSize)
    }
    private fun updateFileSize(downloadedSize: Long) {
        tvFileSize.text = "${formatFileSize(downloadedSize)} / ${formatFileSize(totalSize)}"
    }

    private fun formatFileSize(size: Long): String {
        if (size <= 0) return "0 B"
        val units = arrayOf("B", "KB", "MB", "GB", "TB")
        val digitGroups = (Math.log10(size.toDouble()) / Math.log10(1024.0)).toInt()
        return "${decimalFormat.format(size / Math.pow(1024.0, digitGroups.toDouble()))} ${units[digitGroups]}"
    }
} 